<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col
        :span="24"
        :xs="24"
      >
        <!-- 搜索表单 -->
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          label-width="80px"
        >
          <!-- 支持模糊全局查询 -->
          <el-form-item
            label="搜索"
            prop="allThings"
          >
            <el-input
              v-model="queryParams.allThings"
              placeholder="请输入关键字"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <!-- 搜索顾客姓名或电话 -->
          <el-form-item
            label="顾客信息"
            prop="customerInfo"
          >
            <el-input
              v-model="queryParams.customerInfo"
              placeholder="请输入顾客信息"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <!-- 时间信息，精确到日 -->
          <el-form-item
            label="日期"
            prop="orderDate"
          >
            <el-date-picker
              type="date"
              placeholder="选择开始日期"
              v-model="queryParams.orderDate"
              size="small"
              style="width: 100%;"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
            >搜索</el-button>
            <el-button
              icon="el-icon-refresh"
              size="mini"
              @click="resetQuery"
            >重置</el-button>
          </el-form-item>
        </el-form>

        <!-- 数据操作按钮 -->
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="small"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              icon="el-icon-edit"
              size="small"
              :disabled="single"
              @click="handleUpdate"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              :disabled="multiple"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
          <!-- 以下两个图标需要修改 -->
          <el-col :span="1.5">
            <el-button
              type="success"
              class="take"
              icon="el-icon-timer"
              size="small"
              :disabled="single"
              @click="handleStart"
            >挂账</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              class="take make"
              icon="el-icon-shopping-cart-full"
              size="small"
              :disabled="single"
              @click="handlePay"
            >结账</el-button>
          </el-col>
        </el-row>

        <!-- 数据展示Table -->
        <el-table
          v-loading="loading"
          :data="dataList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="50"
            align="center"
          />
          <el-table-column
            label="ID"
            align="center"
            prop="orderId"
            width="80"
          />
          <el-table-column
            label="订单编号"
            align="center"
            prop="orderNo"
            width="165"
          />
          <el-table-column
            label="顾客姓名"
            align="center"
            prop="customerName"
          />
          <el-table-column
            label="顾客电话"
            align="center"
            prop="customerPhone"
          />
          <el-table-column
            label="会员ID"
            align="center"
            prop="vipId"
          />
          <el-table-column
            label="预约项目"
            align="center"
          >
            <template slot-scope="scope">
              <span
                v-for="(item, index) in scope.row.orderItems"
                :key="item.productId"
              >
                {{ item.productDescription.productName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="发型师"
            align="center"
            prop="tonyName"
          />
          <el-table-column
            label="发型师助理"
            align="center"
            prop="assName"
          />
          <el-table-column
            label="预约开始时间"
            align="center"
            prop="orderTime"
          >
            <template slot-scope="scope">
              {{ formatDate(scope.row.orderTime) }}
            </template>
          </el-table-column>
          <el-table-column
            label="订单状态"
            align="center"
          >
            <template slot-scope="scope">
              {{ formatStatus(scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="small"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                size="small"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页加载 -->
        <!-- eg:handleSizeChange 方法会在用户改变每页显示条目数时被调用 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="queryParams.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </el-col>
    </el-row>

    <!-- 新增/修改对话框 默认不显示 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules1"
        label-width="130px"
      >
        <el-form-item
          label="是否散客"
          prop="isNew"
        >
          <el-switch v-model="form.isNew"></el-switch>
          <!-- <el-input
            v-model="form.isNew"
            placeholder="自动生成"
            disabled
          /> -->
        </el-form-item>
        <el-form-item
          label="顾客姓名"
          prop="customerName"
          v-if="form.isNew"
        >
          <el-input
            v-model="form.customerName"
            placeholder="请输入顾客姓名"
          />
        </el-form-item>
        <el-form-item
          label="顾客电话"
          prop="customerPhone"
          v-if="form.isNew"
        >
          <el-input
            v-model="form.customerPhone"
            placeholder="请输入顾客电话"
          />
        </el-form-item>
        <el-form-item
          label="会员ID"
          prop="vipId"
          v-if="form.isNew===false||form.isNew===undefined||form.isNew===null"
        >
          <el-input
            v-model="form.vipId"
            placeholder="请输入会员ID"
          />
        </el-form-item>
        <el-form-item
          label="预约项目"
          prop="orderItems"
        >
          <el-select
            v-model="form.orderItems"
            placeholder="请选择"
            multiple
          >
            <el-option
              v-for="productItem in ProductOptions"
              :key="productItem.productId"
              :label="productItem.productName"
              :value="productItem.productId"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="发型师"
          prop="tonyName"
        >
          <el-select
            v-model="form.tonyName"
            placeholder="可选"
          >
            <el-option
              v-for="employeesItem2 in filteredEmployees2"
              :key="employeesItem2.eid"
              :label="employeesItem2.ename"
              :value="employeesItem2.ename"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="发型师助理"
          prop="assName""
        >
          <el-select
            v-model="
          form.assName"
          placeholder="可选"
        >
          <el-option
            v-for="employeesItem1 in filteredEmployees1"
            :key="employeesItem1.eid"
            :label="employeesItem1.ename"
            :value="employeesItem1.ename"
          />
          </el-select>
        </el-form-item>
        <el-form-item
          label="预约开始时间"
          required
        >
          <el-col :span="11">
            <el-date-picker
              type="datetime"
              placeholder="选择日期和时间"
              v-model="form.orderTime"
              style="width: 100%;"
            ></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item
          label="单据状态"
          prop="status"
          required
        >
          <el-select
            v-model="form.status"
            placeholder="请选择"
          >
            <el-option
              :label="formatStatus(0)"
              :value="0"
            />
            <el-option
              :label="formatStatus(1)"
              :value="1"
            />
            <el-option
              :label="formatStatus(2)"
              :value="2"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="submitForm"
        >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 支付提示框 -->
    <el-dialog
      title="支付信息"
      :visible.sync="dialogVisible"
      class="pay-dialog"
      width="500px"
    >
      <el-form
        ref="form2"
        :model="form2"
        :rules="rules2"
        label-width="100px"
      >
        <el-form-item
          label="订单编号"
          prop="orderNo"
        >
          <span>{{ form1.orderNo }}</span>
        </el-form-item>
        <!-- 搞勾选框出来 -->
        <!-- v-for="(item1, index) in scope.row.orderItems"
                :key="item1.productId" -->
        <el-form-item
          label="消费项目"
          prop="productName"
        >
          <el-row
            v-for="(item1, index1) in form1.orderItems"
            :key="item1.productName"
          >
            <el-col :span="14">
              <span>{{ item1.productDescription.productName }}&nbsp&nbsp&nbsp&nbsp
                ¥{{ item1.productDescription.price }}</span>
            </el-col>
            <el-col :span="6">
              <el-checkbox
                v-model="item1.buyVip"
                @change="handleCheckboxChange1(item1)"
              >购买次卡</el-checkbox>
            </el-col>
            <el-col :span="4">
              <el-checkbox
                v-model="item1.useVip"
                @change="handleCheckboxChange(item1)"
              >次卡</el-checkbox>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item
          label="发型师"
          prop="tonyName"
        >
          <span>{{ form1.tonyName }}</span>
        </el-form-item>

        <el-form-item
          label="应付金额"
          prop="totalPrice"
        >
          <span>{{ form2.totalPrice }}</span>
        </el-form-item>
        <el-form-item
          label="实付金额"
          prop="amount"
        >
          <el-input
            v-model="form2.amount"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item
          label="支付方式"
          prop="payMethod"
        >
          <el-select
            v-model="form2.payMethod"
            placeholder="请选择"
          >
            <el-option
              :label="formatPayMethod(0)"
              :value="0"
            />
            <el-option
              :label="formatPayMethod(1)"
              :value="1"
            />
            <el-option
              :label="formatPayMethod(2)"
              :value="2"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="备注"
          prop="remark"
        >
          <el-input
            v-model="form2.remark"
            placeholder="请输入"
          />
        </el-form-item>


      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="submitPay"
        >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import { listAllP } from '@/api/pos/product'
  import { listAllE } from '@/api/pos/employees'
  import { listOrderByPage, listAllO, payOrder, aliPay, aliNotify, aliPayMent } from '@/api/pos/sale'
  import { getOrder, addOrder, updateOrder, delOrder, startOrder, addPayment, updateVipTimes } from '@/api/pos/sale'
  import { listAllPackage } from '@/api/pos/package'
  import { addCard } from '@/api/pos/card'
  export default {
    name: "Order",
    data() {
      return {
        // 选中数组
        ids: [],
        // 非单个禁用
        single: false,
        // 勾选1个或多个
        multiple: true,
        // 遮罩层
        loading: false,
        // 表格数据
        dataList: [],
        // 总条数
        total: 0,

        isVisible: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 5,
          allThings: null,
          customerInfo: null,
          // customerName: null,
          // customerPhone: null,
          orderDate: null,
        },
        // 下拉框选项数据
        ProductOptions: [],
        EmployeesOptions: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        dialogVisible: false,
        // 表单
        form: {},
        form1: {},
        form2: {},
        form4: {},
        originalPrices: {},
        // 表单校验
        rules1: {
          //还需要补充
          customerName: [
            { required: true, message: "顾客姓名不能为空", trigger: "blur" },
          ],
          customerPhone: [
            { required: true, message: "顾客电话不能为空", trigger: "blur" },
            // { type: 'number', message: '顾客电话必须是数字', trigger: 'blur' },
          ],
          vipId: [
            { required: true, message: "会员ID不能为空", trigger: "blur" },
          ],
          orderItems: [
            { required: true, message: "预约项目不能为空", trigger: "blur" },
          ],
          // tonyName: [
          //   { required: true, message: "发型师不能为空", trigger: "blur" },
          // ],
          // assName: [
          //   { required: true, message: "发型师助理不能为空", trigger: "blur" },
          // ],
          orderTime: [
            { required: true, message: "预约开始时间不能为空", trigger: "blur" },
          ],
          status: [
            { required: true, message: "单据状态不能为空", trigger: "blur" },
          ],
        },
        rules2: {
          amount: [
            { required: true, message: "实付金额不能为空", trigger: "blur" },
            { pattern: /^(0|[1-9]\d{0,5})(\.\d{1,2})?$/, message: '实付金额必须是数字且最大为999999', trigger: 'blur' },
          ],
          payMethod: [
            { required: true, message: "支付方式不能为空", trigger: "blur" },
          ],
        },
      }
    },
    // 计算属性，可选
    computed: {
      filteredEmployees1() {
        // 筛选出jobTitle为技师的员工
        return this.EmployeesOptions.filter(item => item.jobTitle === '技师');
      },
      filteredEmployees2() {
        // 筛选出jobTitle为技师的员工
        return this.EmployeesOptions.filter(item => item.jobTitle === '发型师');
      },
    },
    // 监控data变化，可选
    watch: {
      'form1.orderItems': {
        handler(newItems, oldItems) {
          // 计算总价并更新 form2.totalPrice
          this.calculateTotalPrice(newItems);
        },
        deep: true // 深度监听 form1.orderItems 内部的变化
      },
    },
    // 生命周期-创建完成，可选
    created() {
      this.getList();
      this.getProductOptions();
      this.getEmployeesOptions();
    },
    // 生命周期-挂载完成，可选
    mounted() {
      this.single = true;
      listAllP().then(response => {
        this.ProductOptions = response.data;
        console.log("成功获取响应数据：", response);
      }).catch(error => {
      });
    },

    // 方法集合
    methods: {
      /** 查询数据列表 */
      /* 此为重点 */
      getList() {
        this.loading = true;
        const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
        const end = start + this.queryParams.pageSize - 1;
        console.log('查询参数:', this.queryParams);
        listOrderByPage(this.queryParams).then(response => {
          console.log("成功获取响应order数据：", response);
          this.total = response.data.length; // 设置分页总数为返回数据的长度
          // 直接将返回的数据赋值给this.dataList
          this.dataList = response.data.slice(start, end + 1);
          this.loading = false;
        });
      },
      // 格式化日期时间
      formatDate(dateTimeStr) {
        if (!dateTimeStr) return '';
        const dateTime = new Date(dateTimeStr);
        const year = dateTime.getFullYear();
        const month = String(dateTime.getMonth() + 1).padStart(2, '0');
        const day = String(dateTime.getDate()).padStart(2, '0');
        const hours = String(dateTime.getHours()).padStart(2, '0');
        const minutes = String(dateTime.getMinutes()).padStart(2, '0');
        const seconds = String(dateTime.getSeconds()).padStart(2, '0');
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
      },
      formatStatus(status) {
        switch (status) {
          case 0:
            return '已预约';
          case 1:
            return '挂账中';
          case 2:
            return '已付款';
          default:
            return '';
        }
      },
      formatUseVip(useVip) {
        switch (useVip) {
          case true:
            return 1;
          case false:
            return 0;
        }
      },
      formatUseVip1(useVip) {
        switch (useVip) {
          case 1:
            return true;
          case 0:
            return false;
        }
      },
      formatPayMethod(PayMethod) {
        switch (PayMethod) {
          case 0:
            return '现金支付';
          case 1:
            return '支付宝支付';
          case 2:
            return '银行卡划扣';
          default:
            return '';
        }
      },
      /** 处理分页 */
      handleSizeChange(val) {
        this.queryParams.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.queryParams.pageNum = val;
        this.getList();
      },
      /** 查询下拉列表选型 */
      getEmployeesOptions() {
        // 访问后端接口，查外键所有对象
        // 结果赋值this.EmployeesOptions
        listAllE().then(response => {
          this.EmployeesOptions = response.data;
          console.log("成功获取响应数据：", response);
        })
      },
      getProductOptions() {
        // 访问后端接口，查外键所有对象
        // 结果赋值this.ProductOptions

      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.orderId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.orderDate = this.formatDateToString(this.queryParams.orderDate);
        this.queryParams.pageNum = 1;
        this.getList();
      },
      formatDateToString(date) {
        if (!(date instanceof Date)) {
          return '';
        }
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.$refs.queryForm.resetFields();
        this.getList();
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        /* 可能会读取不到orderId? */
        const orderId = row.orderId || this.ids
        this.$confirm('是否确认删除编号为"' + orderId + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return delOrder(orderId);
          })
          .then(() => {
            this.getList(); // 刷新数据
            this.$message.success("删除成功");
          })
          .catch(() => { });
      },
      /** 表单初始化 */
      resetForm() {
        // 可进行数据初始化工作，经测试好像没必要
        this.form = {
          orderId: null,
          orderItems: [],
          customerName: null,
          customerPhone: null,
          vipId: null,
          tonyName: null,
          assName: null,
          orderTime: null,
          status: null,
        }
      },
      resetForm1() {
        this.form1 = {
          orderId: null,
          orderItems: [],
          customerName: null,
          customerPhone: null,
          tonyName: null,
          assName: null,
          orderTime: null,
          status: null,
        }
      },
      resetForm2() {
        this.form2 = {
          orderId: null,
          totalPrice: null,
          amount: null,
          payMethod: null,
          remark: null,
        }
      },
      /* 新增修改订单 */
      /** 新增按钮操作 */
      handleAdd() {
        this.resetForm();
        this.open = true;
        this.title = "添加数据";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.resetForm();
        const orderId = row.orderId || this.ids; // 获取当前订单的 orderId
        getOrder(orderId).then(response => {
          console.log("成功获取修改0响应数据：", response);
          // 获取订单数据
          const orderData = response.data;
          // 获取订单的产品数据
          const orderItems = orderData.orderItems;
          // 初始化选项数组
          const selectedProductIds = [];
          // 遍历订单的产品数据，组成选项数组
          orderItems.forEach(item => {
            selectedProductIds.push(item.productId);
          });
          // 将选项数组赋值给表单项
          this.form.orderItems = selectedProductIds;
          // 更新其他字段
          this.form.vipId = orderData.vipId;
          this.form.customerName = orderData.customerName;
          this.form.customerPhone = orderData.customerPhone;
          this.form.tonyName = orderData.tonyName;
          this.form.assName = orderData.assName;
          this.form.orderTime = orderData.orderTime;
          this.form.status = orderData.status;
          // 设置当前订单的 orderId
          this.form.orderId = orderId;
          // 打印订单数据，确保数据正确
          console.log("成功获取修改1响应数据：", response);
          // 打开对话框
          this.open = true;
          this.title = "修改数据";
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            // 构建包含所选产品的productId的数组
            const selectedProductIds = this.form.orderItems;
            // 将每个子数组中的productId更新为所选产品的productId
            this.form.orderItems = selectedProductIds.map(productId => ({ productId }));
            // 如果 orderId 是数组，则取第一个元素作为单个值
            if (Array.isArray(this.form.orderId)) {
              this.form.orderId = this.form.orderId[0];
            }
            console.log("提交的表单数据：", this.form); // 打印 form 数据
            if (this.form.orderId != null) {
              // 如果订单已存在，则调用更新订单的接口
              updateOrder(this.form).then(response => {
                this.$message.success(response.msg);
                this.getList();
                this.cancel();
              })
            } else {
              // 如果订单不存在，则调用添加订单的接口
              addOrder(this.form).then(response => {
                console.log("成功获取add响应数据：", response);
                this.$message.success(response.msg);
                this.getList();
                this.cancel();
              })
            }
          }
        });
      },
      handleStart(row) {
        const orderId = row.orderId || this.ids;
        getOrder(orderId).then(response => {
          if (response.data.status !== 0) {
            this.$message.error("只有预约中的订单可以挂账！");
            return;
          }
          this.$confirm('是否确认挂账?', "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(function () {
              return startOrder(orderId);
            })
            .then(() => {
              this.getList();
              this.$message.success("挂账成功");
            })
            .catch(() => { });
        });
      },
      /* 支付功能 */
      handlePay(row) {
        this.resetForm1();
        this.resetForm2();
        const orderId = row.orderId || this.ids;
        listAllPackage().then(response => {
          this.form4 = response.data;
          console.log("成功获取次卡套餐响应数据：", response.data);
        }).catch(error => {
        });
        payOrder(orderId).then(response => {
          console.log("成功获取支付0响应数据：", response);
          if (response.data.status !== 1) {
            this.$message.error("只有挂账中的订单可以结账！");
            return;
          }
          this.form1 = response.data;
          this.form1.orderItems.forEach(item => {
            item.useVip = this.formatUseVip1(item.useVip);
          });
          this.form2.orderId = response.data.orderId;
          // 打印订单数据，确保数据正确
          console.log("成功获取支付1响应数据：", this.form1);
          // 打开对话框
          this.dialogVisible = true;
          this.title = "支付信息";
        });
      },
      /* 次卡勾选框 */
      handleCheckboxChange(item) {
        console.log('次卡框框', item);
        const nowProductId = item.productId;
        const queryVipProductId = this.form1.vips.map(vip => vip.vipItems.map(vipItem => vipItem.vipPackage.productId)) || null;
        const usedTimes = this.form1.vips.map(vip => vip.vipItems.find(vipItem => vipItem.vipPackage?.productId === nowProductId)?.usedTimes);
        const times = this.form1.vips.map(vip => vip.vipItems.find(vipItem => vipItem.vipPackage?.productId === nowProductId)?.vipPackage.times);
        console.log("xxxxx", nowProductId, queryVipProductId, usedTimes, times);
        if (queryVipProductId && queryVipProductId.flat().includes(nowProductId)) {
          if (usedTimes[0] >= times[0]) {
            if (!item.buyVip) {
              this.$message.error("您的次卡次数已用完!");
              item.useVip = false;
            }
            return;
          }
        } else {
          if (!item.buyVip) {
            this.$message.error("您没有该次卡!");
            item.useVip = false;
          }
        }
      },
      handleCheckboxChange1(item) {
        if (this.form1.vipId === null) {
          this.$message.error("您还没有会员卡!");
          item.buyVip = false;
          return;
        }
        const i = this.form4.findIndex(item9 => item9.productId === item.productId);
        if (i === -1) {
          this.$message.error("该项目没有次卡套餐!");
          item.buyVip = false;
        } else {
          if (item.buyVip) {
            if (!item.useVip) {
              item.useVip = true;
            }
          } else {
            if (item.useVip) {
              item.useVip = false;
            }
          }
        }
        console.log('购买次卡框框', item);
      },
      /* 计算总金额 */
      calculateTotalPrice(items) {
        // 遍历 orderItems，累加每个项目的 price
        const totalPrice = items.reduce((total, item) => {
          // 如果 useVip 为 true，则将价格设为 0
          const price = item.useVip ? 0 : item.productDescription.price;
          const i = this.form4.findIndex(item9 => item9.productId === item.productId);
          if (i === -1) { return total + price; }
          else {
            const buyVipPrice = item.buyVip ? (item.productDescription.price * this.form4[i].times) : 0;
            return total + price + buyVipPrice;
          }
        }, 0);
        // 更新 form2.totalPrice
        this.form2.totalPrice = totalPrice;
      },
      /* 支付提交 */
      submitPay: function () {
        this.$refs["form2"].validate(valid => {
          if (valid) {
            this.submitPay0();
          }
        });
      },
      submitPay0: async function () {
        if (this.form2.payMethod === 1) {
          console.log(this.form1.orderNo, this.form2.amount, this.form1.customerName);
          const a = this.form1.orderNo;
          const b = this.form2.amount;
          const c = "MISP美发店";
          // try {
          //   await aliPay(a, b, c);
          // } catch (error) {
          //   console.error("aliPay接口调用出错：", error);
          //   // 在这里处理接口调用出错的情况，比如记录日志或者忽略错误
          // }
          // 构建 URL，将参数添加到其中
          const url = `http://localhost:8081/alipay/pay?orderNo=${a}&amount=${b}&name=${c}`;
          // 发送 GET 请求
          fetch(url)
            .then(response => {
              if (!response.ok) {
                console.log('没事不用管1，因为这个接口用不了');
              }
              return response.text();
            })
            .then(data => {
              console.log('没事不用管2，因为这个接口用不了');
            })
            .catch(error => {
              console.log('没事不用管3，因为这个接口用不了');
            });
          setTimeout(() => {
            window.open(`http://localhost:8081/alipay/pay?orderNo=${a}&amount=${b}&name=${c}`);
          }, 1000);
          // 处理确认对话框点击事件
          try {
            await this.$confirm('您是否已经支付?', "请确认", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "info",
            })
              .then(() => {
                aliPayMent(a).then(response => {
                  console.log("支付结果：", response.data);
                  if (response && response.data && response.data.tradeStatus === "TRADE_SUCCESS") {
                    console.log("支付宝成功第一步！");
                    this.submitPay1();
                  } else {
                    this.$message.error("支付失败或未获取到支付状态！");
                  }
                })
              })
          } catch (error) {
            // console.error("确认对话框出错：", error);
            // 在这里处理确认对话框出错的情况，比如记录日志或者忽略错误
          }
        } else {
          this.submitPay1();
        }
      },


      /* 支付更新表 */
      submitPay1: function () {
        this.form2.amount = parseFloat(this.form2.amount);
        console.log("this.form2", this.form2);
        console.log("this.form1", this.form1);
        addPayment(this.form2).then(response => {
          console.log("更新支付表：", response);
          this.form1.orderItems.forEach(item => {
            if (item.buyVip === true) {
              const i = this.form4.findIndex(item9 => item9.productId === item.productId);
              const findVipPackageId = this.form4[i].packageId;
              const form5 = {
                vipId: this.form1.vipId,
                vipPackageId: findVipPackageId,
                usedTimes: 0,
              }
              addCard(form5).then(response => {
                console.log("购买次卡", response);
              })
            }
          })
          this.form1.orderItems.forEach(item => {
            if (item.useVip === undefined || null) {
              item.useVip = false;
            }
            // 将每个项目的 useVip 属性格式化为 '0' 或 '1'
            item.useVip = this.formatUseVip(item.useVip);
          })
          this.form1.status = 2;
          updateOrder(this.form1).then(response => {
            console.log("更新订单状态：", response);
          })
          updateVipTimes(this.form1.orderId).then(response => {
            console.log("更新次卡次数：", response);
            this.getList();
            this.cancel();
            this.$message.success("支付成功！");
          })
        }).catch(error => {
          console.error("支付失败：", error);
          this.$message.error("支付信息有误或您已有支付！");
        });
      },
      /** 取消按钮 */
      cancel() {
        this.open = false;
        this.dialogVisible = false;
        this.title = "";
        this.resetForm();
      },
    }
  }
</script>

<style
  scoped
  lang="scss"
>
  /* 修改 take 类型按钮的背景色 */
  .take {
    background-color: #ff9800;
  }

  /* 按钮在不可点击状态下的样式 */
  .take[disabled] {
    opacity: 0.5;
    /* 设置透明度为 50% */
    cursor: not-allowed;
    /* 将鼠标指针设置为禁止 */
  }

  .make {
    background-color: rgb(68, 196, 166);
  }
</style>